﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using WLYT.Common;
using WLYT.Domain.Model;

namespace WLYT.Admin.WebApi.Component.log4net
{
    public class CustomMessageHandler : DelegatingHandler
    {
        private static readonly ILog loginfo = LogManager.GetLogger("loginfo");
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var url = request.RequestUri.AbsoluteUri;
            if (!url.ToLower().Contains("/api/wms/") && !url.Contains("/api/agv/") || url.Contains("api/Wms/ILckt/") || !url.Contains("api/Order/unpack_TBJ"))
            {
                return base.SendAsync(request, cancellationToken);
            }
            long startTime = DateTime.Now.Ticks;
            LogRecord log = new LogRecord
            {
                Method = request.Method.ToString(),
                RequestUri = url,
                IP = StringHelper.GetIP()
            };
            if (request.Content != null)
            {
                log.RequestContent = request.Content.ReadAsStringAsync().Result;
            }

            return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((task) =>
            {
                log.ResponseContent = task.Result.Content == null ? "Bad Request" : task.Result.Content.ReadAsStringAsync().Result;
                if(!log.RequestUri.Contains("QueryWarehousOut_SMT") || !log.ResponseContent.Contains("\"Data\":[]"))
                {
                    log.Timer = (int)((DateTime.Now.Ticks - startTime) / 10000);
                    loginfo.Info(log);
                }
                return task.Result;
            });
        }
    }
}